<?php

namespace app\wechat\controller;
use think\Controller;
use think\Session;
use app\wechat\lib\OAuth;

class Auth extends Controller
{
    // 引导进入授权页面
    public function index()
    {
        $redirectUri = $this->request->domain() . '/wechat/auth/callback';
        $state       = '';
        $uri = OAuth::uri($redirectUri, $state);
        $this->redirect($uri);
    }

    // 授权回调页面
    public function callback()
    {
        $code = $this->request->get('code/s','');
        $stat = $this->request->get('state/s','');

        // 通过code换取网页授权access_token
        /*
        {
            "access_token":"ACCESS_TOKEN",
            "expires_in":7200,
            "refresh_token":"REFRESH_TOKEN",
            "openid":"OPENID",
            "scope":"SCOPE"
        }
        */
        $accessToken = OAuth::accessToken($code);
        // p($accessToken);die;

        // 拉取用户信息
        /*
        {
            "openid":" OPENID",
            "nickname": NICKNAME,
            "sex":"1",
            "province":"PROVINCE"
            "city":"CITY",
            "country":"COUNTRY",
            "headimgurl":"http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
            "privilege":["PRIVILEGE1" "PRIVILEGE2"],
            "unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL" （没并入开放平台时，没有此字段）
        }
        */
        $uinfo = OAuth::uinfo($accessToken['access_token'], $accessToken['openid']);
        // p($uinfo);die;

        // 写入Session
        $wechat = array(
            'unionid'    => isset($uinfo['unionid']) ? $uinfo['unionid'] : '',
            'openid'     => $uinfo['openid'],
            'nickname'   => $uinfo['nickname'],
            'headimgurl' => $uinfo['headimgurl'],
            'sex'        => $uinfo['sex'],
            'country'    => $uinfo['country'],
            'province'   => $uinfo['province'],
            'city'       => $uinfo['city']
            );
        Session::set('wechat', $wechat);

        $callbackUri = Session::pull('callbackUri');
        $this->redirect($callbackUri);
    }
}
